#include "twocut_funcs.h"
Mat step_one(Mat image){
    Mat src=image;
    Mat dst;
    cvtColor(src, dst, COLOR_BGR2GRAY);
    src=dst;
    inRange(src, Scalar(157,157,157), Scalar(200,200,200), dst);
    return dst;
}
void Clear_MicroConnected_Areas(cv::Mat src, cv::Mat &dst, double min_area)
      {
          // 备份复制
          dst = src.clone();
          std::vector<std::vector<cv::Point> > contours;  // 创建轮廓容器
          std::vector<cv::Vec4i>     hierarchy;

          // 寻找轮廓的函数
          // 第四个参数CV_RETR_EXTERNAL，表示寻找最外围轮廓
          // 第五个参数CV_CHAIN_APPROX_NONE，表示保存物体边界上所有连续的轮廓点到contours向量内
          cv::findContours(src, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point());

          if (!contours.empty() && !hierarchy.empty())
          {
              std::vector<std::vector<cv::Point> >::const_iterator itc = contours.begin();
              // 遍历所有轮廓
              while (itc != contours.end())
              {
                  // 定位当前轮廓所在位置
                  cv::Rect rect = cv::boundingRect(cv::Mat(*itc));
                  // contourArea函数计算连通区面积
                  double area = contourArea(*itc);
                  // 若面积小于设置的阈值
                  if (area < min_area)
                  {
                      // 遍历轮廓所在位置所有像素点
                      for (int i = rect.y; i < rect.y + rect.height; i++)
                      {
                          uchar *output_data = dst.ptr<uchar>(i);
                          for (int j = rect.x; j < rect.x + rect.width; j++)
                          {
                              // 将连通区的值置0
                              if (output_data[j] == 255)
                              {
                                  output_data[j] = 0;
                              }
                          }
                      }
                  }
                  itc++;
              }
          }
      }


Mat step_two(Mat image){
    Mat src=image;
    Mat kernel_1,kernel_2,dst;
    kernel_1=getStructuringElement(MORPH_RECT, Size(3,3));
    kernel_2=getStructuringElement(MORPH_RECT, Size(5,5));
    erode(src, dst, kernel_1);
    src=dst;
    dilate(src, dst, kernel_2);
    src=dst;
    Clear_MicroConnected_Areas(src, dst, 1500);
    src=dst;
    dilate(src, dst, kernel_2);
    return dst;
}

Mat step_three(Mat image,Mat origin){
    Mat src=image;
    Mat dst;
    vector<vector<cv::Point>> contours;
    vector<cv::Vec4i> hierarchy;
    findContours(src, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    dst = origin;
    drawContours(dst, contours, -1, Scalar(0, 0, 255));
    return dst;
}
